import random  # 用于生成随机码
from django.core.mail import send_mail  # 发送邮件模块
# from app01.models import EmailVerifyRecord  # 邮箱验证model
from django.conf import settings    # setting.py添加的的配置信息



class EmailUtil:
    def __init__(self):
        pass

    @staticmethod
    # 生成随机字符串
    def random_str(randomlength=8):
        """
        随机字符串
        :param randomlength: 字符串长度
        :return: String 类型字符串
        """
        str = ''
        chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
        length = len(chars) - 1
        for i in range(randomlength):
            str += chars[random.randint(0, length)]
        return str


    # 发送电子邮件
    def send_code_email(email, email_type="register"):
        """
        发送电子邮件
        :param email: 要发送的邮箱
        :param email_type: 邮箱类型
        :return: True/False
        """
        # email_record = EmailVerifyRecord()
        # 将给用户发的信息保存在数据库中
        # code = EmailUtil.random_str(16)
        code = str(random.randrange(100000, 999999))

        # email_record.code = code
        # email_record.email = email
        # email_record.email_type = email_type
        # email_record.send_time = datetime.datetime.now()
        # email_record.save()
        # 初始化为空
        email_title = ""
        email_body = ""
        # 如果为注册类型
        try:
            if email_type == "register":
                email_title = "重庆大学大数据教学平台——注册激活"
            else:
                email_title = "重庆大学大数据教学平台"
            email_body = "{0}, 该验证码有效时间为5分钟，请及时进行验证。".format(code)
            # 发送邮件
            send_status = send_mail(email_title, email_body, settings.EMAIL_FROM, [email])
            if not send_status:
                print("EmailUtil.send_code_email, 邮件发送失败.send_status出错")
                return None

            print("EmailUtil.send_code_email, 邮件发送成功:code = " + code)
            return code
        except Exception as e:
            print("EmailUtil.send_code_email, 邮件发送失败：" + str(e))
            return None

    def send_do_task_email(email, task_name_list,course_name):
        """
        发送任务执行成功的邮件
        :param email: 接收邮件的邮箱
        :param task_name_list: 任务名称列表
        :return: True/False
        """
        try:
            email_title = "重庆大学大数据教学平台"
            task_str ='【'+'】、【'.join(task_name_list)+'】'
            email_body = f"您的【{course_name}】班课的任务{task_str}还未提交，请注意截止时间，及时完成任务。\n平台链接：http://172.20.216.103"
            # 发送邮件
            print('email = ', email)
            print('email_body = ', email_body)
            send_status = send_mail(email_title, email_body, settings.EMAIL_FROM, [email])
            if not send_status:
                print("EmailUtil.send_do_task_email, 邮件发送失败")
                return None
        
        except Exception as e:
            print("EmailUtil.send_code_email, 邮件发送失败：" + str(e))
            raise e